package com.study.servlet.session.prac02;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.study.servlet.session.prac02.domain.Book;

/**
* @Name: BuyBook
* @Description: Session应用：实现购物车
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-3-3 下午3:52:02 
* @Version: V1.0
 */
public class BuyBook extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8") ;
		PrintWriter out = response.getWriter() ;
		//获取请求参数
		request.setCharacterEncoding("UTF-8") ; //设置请求参数编码，适用于POST提交
		String id = request.getParameter("id") ;
		//显示书籍详情
		Book book = BookDB.getBookById(id) ;
		out.write("购买书籍详情如下：<br/>") ;
		String showAllBooksUrl = request.getContextPath() + "/servlet/ShowAllBooks" ;
		String url = response.encodeURL(showAllBooksUrl) ;
		out.write(book + "&nbsp;&nbsp;&nbsp;&nbsp;" +
				"<a href="+ url +">继续购买</a>") ;
		//将购买书籍加入购物车
		HttpSession session = request.getSession() ;
		List<Book> list = (List<Book>) session.getAttribute("CART") ;
		if(list == null || list.size() == 0) {
			list = new ArrayList<Book>() ;
			session.setAttribute("CART", list) ;
		}
		list.add(book) ;
		out.flush() ;
		out.close() ;
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

}
